export const BASE_URL = process.env.NODE_ENV === 'development' ? 'http://121.4.90.147/compass' :
    'http://121.4.90.147/compass'

// export const BASE_URL = process.env.NODE_ENV === 'development' ? 'https://app.zbzedu.com/prod-api' :
//     'https://app.zbzedu.com/prod-api'
console.log(process.env.NODE_ENV)

import {TOAST} from "./util";

export const request = (obj) => {
  if (!obj.not_loading) {
    uni.showLoading({
      mask: true,
      title: obj.lodingTxt || '数据加载中'
    })
  }
  wx.showNavigationBarLoading();
  let info = uni.getStorageSync('zbz_user');
  let token = info && info.token
  return new Promise((resolve, reject) => {
    uni.request({
      url: BASE_URL + obj.url,
      data: obj.data,
      method: obj.method || 'GET',
      header: obj.header ? obj.header :( !obj.token ? {
        'Authorization': `${token || ''}`,
        'type': '1',
        'Content-Type': 'application/json'
      } : {'Content-Type': 'application/json'}),
      success: (res) => {
        uni.hideLoading()
        if (res && res.data.code == 401) {
          uni.removeStorageSync('zbz_user');
          // $App.checkToken();
          if (obj.platfom != 'weixin') {
            uni.reLaunch({
              url: `/pages/login/wx_login?backUrl=${getBackUrl()}`
            });
          }
          return
        }
        if (obj.platfom == 'weixin') {
          resolve(res.data)
          return;
        } else {
          if (res.data.code == 200 || res.errcode == 0) {
            resolve(res.data)
          } else {
            if (obj.errorFn) {
              reject(res.data)
            }
            if(!res) {
              TOAST('服务器繁忙,请稍后再试')
            } else {
              TOAST(res.data.msg || res.body.msg)
            }
          }
        }
      },
      fail(err) {
        uni.hideLoading()
        reject(err)
      },
      complete() {
        uni.hideNavigationBarLoading();
      }
    });
  })
}

export const checkToken = () => {
  var user = localStorage.getItem('user');
  if(user && JSON.parse(user).token) {
    $App.ajax({
      url: '/app/base/firstLogin',
      type: 'get',
      data: {},
      success: function(ret) {
        if (ret.data) {
          $App.openWin({
            name: 'html/login/set_password',
            url: 'widget://html/login/set_password.html'
          })
        } else{
          return true;
        }
      }
    })
  } else {
    $App.openWin({
      name: 'html/login/login_password',
      url: 'widget://html/login/login_password.html'
    })
    return false;
  }
}

export const getBackUrl = () => {
  var pages = getCurrentPages()
  let {route,options} = pages[pages.length - 1]
  if (options && Object.keys(options).length) {
    let paramsStr = '#'
    for(var n in options) {
      paramsStr += `${n}*${options[n]}@`
    }
    paramsStr = paramsStr.substr(0, paramsStr.length - 1)
    return route + paramsStr
  } else {
    return route
  }
}
